package com.itheima.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.exception.MyException;
import com.itheima.common.result.JsonResult;
import com.itheima.entity.User;
import com.itheima.entity.dto.UserDTO;
import com.itheima.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhengbinghua
 * @since 2023-03-02
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
public class UserController {
@Autowired
    private UserService userService;
@Autowired
   private RedisTemplate redisTemplate;
String key="1234";
@ApiOperation(value = "发送短信")
@PostMapping("sendMsg")
public JsonResult sendmsg(@RequestBody User user){
//获取手机号
    String phone = user.getPhone();
    //判断手机号是否存在
    LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(User::getPhone,phone);
    //手机号不存在，报错
    User one = userService.getOne(wrapper);
    if (null==one){
        throw new MyException(404, "手机号不存在，短信发送失败");
    }
    //随机数工具生成验证码4位数
    String code = RandomUtil.randomString(6);
    //调用阿里云发送验证码
    //验证码存入redis，设置过期时间
    redisTemplate.opsForValue().set("com.itheima.client.sendmsg", code, 1800, TimeUnit.SECONDS);
    //返回前端
    return JsonResult.success(code);

}
@PostMapping("login")
@ApiOperation(value = "用户登陆")
public JsonResult userLogin(@RequestBody UserDTO userDTO){
    //判断手机号是否存在
    LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(User::getPhone, userDTO.getPhone());
    User user = userService.getOne(wrapper);
    if (null==user){
        throw new MyException(404, "手机号不存在，登陆失败！");
    }
    //取出短信验证码
    if (redisTemplate.hasKey("com.itheima.client.sendmsg")==null){
       throw new MyException(404, "验证码已过期，请重新获取！");
    }
   String code = (String) redisTemplate.opsForValue().get("com.itheima.client.sendmsg");
    //签发token
    String token = JWT.create().setKey(key.getBytes(StandardCharsets.UTF_8))
            .setPayload("time", System.currentTimeMillis())//迷惑信息
            .setPayload("phone", userDTO.getPhone())//电话
            .setPayload("id", userDTO.getId()).sign();//用户id
    //存入redis
    redisTemplate.opsForValue().set(token, "1", 3600, TimeUnit.SECONDS);
    //返回结果
    return JsonResult.success(token);

}
@PostMapping("logout")
@ApiOperation(value = "用户登出")
public JsonResult userLogout(String token){
    //判断token是否存在
    if (redisTemplate.hasKey(token)==null){
        return JsonResult.fail("token不存在！");
    }
    redisTemplate.delete(token);
    return JsonResult.fail("登出成功！");
}
}
